﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using QW.Core.AutoTasks;

namespace QW.Found.Extensions
{
    /// <summary>
    /// 任务构建器
    /// </summary>
    public static class TaskExtensions
    {
        /// <summary>
        /// 注册 任务中心
        /// </summary>
        /// <param name="services"></param>
        /// <param name="projectTypes"></param>
        public static void AddTaskCenter(this IServiceCollection services, List<Type> projectTypes)
        {
            var types = projectTypes
               .Where(p => !p.IsInterface && !p.IsAbstract && !p.IsSealed)
               .Where(p => typeof(ITask).IsAssignableFrom(p)).ToList();

            foreach (var type in types)
                services.AddSingleton(typeof(ITask), type);
        }

        /// <summary>
        /// 启动任务框架
        /// </summary>
        public static void UseTaskCenter(this IApplicationBuilder app)
        {
            var lifetime = app.ApplicationServices.GetService<IHostApplicationLifetime>();
            //在应用启动时完成任务中心的注册与启动
            lifetime?.ApplicationStarted.Register(() =>
            {
                var tasks = app.ApplicationServices.GetServices<ITask>();
                var center = app.ApplicationServices.GetService<ITaskCenter>();
                center?.Register(tasks);
                center?.Start();
            });
        }
    }
}
